package com.wwwc.index.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.Address;
import javax.mail.internet.MimeMessage;
import javax.mail.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class SendMailTestServlet extends HttpServlet {
    private String username = null;
    private String password = null; 

   public void doGet(HttpServletRequest request,  HttpServletResponse response)
	throws IOException, ServletException 
    {
	doPost(request, response);
	return;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
	PrintWriter out  = response.getWriter();
        String action    = request.getParameter("action");
	String user_ip   = request.getRemoteAddr();

	HttpSession session = request.getSession(true);

	response.setContentType("text/html");

	if (action == null) {
	    out.println((new SendMailBean()).mailForm(session.getId(),"SendMailTestServlet?action=send"));
	    return;
	}

	if(action.equals("send")) {
	    String euser   ="William.Li";
	    String epass   ="li0578";
	    String from    = "William.Li@3WCenter.com";//request.getParameter("mailfrom");
	    String to      = request.getParameter("mailto");
	    String subject = request.getParameter("mailsubject");
	    String content = request.getParameter("mailcontent");

	    try {
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Example Mail Sending Results</title>");
		out.println("</head>");
		out.println("<body bgcolor=\"white\">");
		
		SendMail smail = new SendMail();
		if(!smail.send(from, euser, epass, to, subject, content)) {
		    out.println(smail.getError());
		}
		else {
		    out.println("OK");
		}

		out.println("</body>");
		out.println("</html>");
	    }
	    catch (Exception e) {
		out.println("E-Mail Server:Error");
		System.out.println("SendMailTestServlet:Error:"+e);
		return;
	    }     
	    return;   
	}
	else {
	    out.println(action);
	}
    }

    private class SmtpAuthenticator extends Authenticator {
	protected PasswordAuthentication getPasswordAuthentication() {
	    return new PasswordAuthentication (username, password); 
	} 
    } 
}
